package com.hd.crdao.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.base.MyBaseAdapter;
import com.hd.crdao.bean.ReportListBean;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.PinyinUtils;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 *
 *@author Administrator
 *@date 2017/6/27 0027
 */
public class SearchReportActivity extends BaseActivity implements  OnRefreshListener {
    @BindView(R.id.searchEt)
    EditText mSearchEt;
    @BindView(R.id.cancel)
    TextView mCancel;
    Handler mHandler = new Handler();
    ReportListAdapter mReportListAdapter;
    public ReportListBean mReportListBean;
    public String mBusinessid;
    public String mTrim;
    @BindView(R.id.listview)
    ListView mListview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_searchreport;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initListener() {
        //设置监听事件
        mSearchEt.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // 修改回车键功能
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchReportActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //接下来在这里做你自己想要做的事，实现自己的业务。
                    mTrim = mSearchEt.getText().toString().trim();
                    mRefreshLayout.autoRefresh();
                }

                return false;
            }
        });

        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                position = position - 1;
                List<ReportListBean.PayListBean> payList = mReportListBean.getPayList();
                if (payList != null) {
                    ReportListBean.PayListBean payListBean = payList.get(position);
                    String plStatus = payListBean.getPlStatus();
                    String vincode = payListBean.getBuy4s().getB4Vincode();
                    String buyId = payListBean.getBuy4s().getId();
                    String b4Code = payListBean.getBuy4s().getB4Code(); //查询结果返回码
                    String payListId = payListBean.getId();
                    if (TextUtils.equals("1", plStatus)) {
                        Intent i = new Intent(UIUtils.getContext(), FirmOrderActivity.class);
                        i.putExtra("vin", vincode);
                        i.putExtra("buyid", buyId);
                        i.putExtra("payListId", payListId);
                        startActivity(i);
                    } else if (TextUtils.equals("0", plStatus)) {
                        if (TextUtils.equals("1104", b4Code)) {
                            final Intent intent = new Intent(UIUtils.getContext(), ReportDetailActivity.class);
                            OkHttpUtils.post().url(Constants.REPORT_DETAIL_URL).addParams("payListId", payListId).build().execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ALog.d("error");
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    intent.putExtra("reportinfo", response);
                                    startActivity(intent);
                                }
                            });
                        }
                    }

                }
            }
        });

        mRefreshLayout.setOnRefreshListener(this);

    }

    @Override
    protected void initData() {
        mBusinessid = SPUtils.getString("businessid", "");
    }


    @OnClick(R.id.cancel)
    public void onViewClicked() {
        finish();
    }

    /**
     * 访问网络请求数据填充
     *
     * @param pageNo          分页
     * @param pageSize        分页的条数
     * @param carBusinessId   车商id
     * @param status          状态
     * @param vinOrSeriesName vin后六位或者车系
     */
    private void requestData(String pageNo, String pageSize, String carBusinessId, String status, String vinOrSeriesName) {

        try {
            OkHttpUtils.post().url(Constants.REPORTLIST_URL).addParams("pageNo", pageNo).addParams("pageSize", pageSize)
                    .addParams("carBusinessId", carBusinessId)
                    .addParams("status", status).addParams("vinOrSeriesName", vinOrSeriesName)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    MyToast.show("数据加载失败,请检查网络...");
                    mRefreshLayout.finishRefresh();
                }

                @Override
                public void onResponse(String response, int id) {
                    ALog.d(response);
                    Gson gson = new Gson();
                    mReportListBean = gson.fromJson(response, ReportListBean.class);
                    String success = mReportListBean.getSuccess();   //获取成功码
                    List<ReportListBean.PayListBean> payList = mReportListBean.getPayList();
                    if (TextUtils.equals("00", success)) {
                        if (payList.size() == 0) {
                            MyToast.show("未查询到相关数据");
                        } else {
                            mReportListAdapter = new ReportListAdapter(payList);
                            mListview.setAdapter(mReportListAdapter);
                        }
                    } else {
                        MyToast.show(success);
                    }
                    mRefreshLayout.finishRefresh();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRefresh(final RefreshLayout refreshlayout) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData("", "", mBusinessid, "", mTrim);
            }
        },1000);
    }


    /**
     * 4S查询报告列表的适配器
     */
    public class ReportListAdapter extends MyBaseAdapter<ReportListBean.PayListBean> {

        public ReportListAdapter(List<ReportListBean.PayListBean> payList) {
            super(payList);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(UIUtils.getContext(), R.layout.item_reportlist, null);
                holder = new ViewHolder();
                holder.mIvLog = (ImageView) convertView.findViewById(R.id.iv_log);
                holder.mBrand = (TextView) convertView.findViewById(R.id.tv_brand);
                holder.mStatus = (TextView) convertView.findViewById(R.id.tv_status);
                holder.mVin = (TextView) convertView.findViewById(R.id.tv_vin);
                holder.mTime = (TextView) convertView.findViewById(R.id.time);
                holder.mDelete = (ImageButton) convertView.findViewById(R.id.delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ReportListBean.PayListBean payListBean = mDataSets.get(position);
            String plStatus = payListBean.getPlStatus();   //获取支付状态
            String b4Code = payListBean.getBuy4s().getB4Code(); //查询结果返回码
            String b4Rescode = payListBean.getBuy4s().getB4Rescode();
            String b4Resmsg = payListBean.getBuy4s().getB4Resmsg();
            String b4Brand = payListBean.getBuy4s().getB4Brand();
            String b4Ordermsg = payListBean.getBuy4s().getB4Ordermsg(); //查询结果提示信息
            String b4Seriesname = payListBean.getBuy4s().getB4Seriesname();
            if (b4Brand == null) {
                holder.mBrand.setText("品牌待识别");
                Drawable img = UIUtils.getResources().getDrawable(R.drawable.about_1_1_3x);
                holder.mIvLog.setImageDrawable(img);
            } else {
                holder.mBrand.setText(b4Seriesname);
                String pingYin = PinyinUtils.getPingYin(b4Brand).toLowerCase();
                ALog.d(pingYin + "----------------------------------");
                int resID = getResources().getIdentifier(pingYin, "drawable", "com.hd.crdao");
                if (resID == 0) {   //没有这张资源文件
                    Drawable img = UIUtils.getResources().getDrawable(R.drawable.about_1_1_3x);
                    holder.mIvLog.setImageDrawable(img);
                } else {
                    Drawable img = UIUtils.getResources().getDrawable(resID);
                    holder.mIvLog.setImageDrawable(img);
                }
            }

            if (TextUtils.equals("0", plStatus)) {
                if (TextUtils.equals("0", b4Code)) {
                    holder.mStatus.setText("查询中");
                } else if (TextUtils.equals("1", b4Code)) {
                    if (TextUtils.equals("1104", b4Rescode)) {
                        holder.mStatus.setText("已出报告");
                    } else {
                        holder.mStatus.setText(b4Ordermsg);
                    }
                } else {
                    holder.mStatus.setText(b4Resmsg);
                }
            } else if (TextUtils.equals("1", plStatus)) {
                holder.mStatus.setText("预支付");
            } else if (TextUtils.equals("2", plStatus)) {
                holder.mStatus.setText("失败");
            } else if (TextUtils.equals("3", plStatus)) {
                holder.mStatus.setText("交易数据不一致");
            } else {
                holder.mStatus.setText("退款");
            }
            holder.mVin.setText("VIN : " + payListBean.getBuy4s().getB4Vincode());
            holder.mTime.setText("查询时间 : " + payListBean.getUpdateDate());

            holder.mDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog(position);
                }
            });

            return convertView;
        }

        /**
         * 弹出确认的对话框
         *
         * @param position
         */
        private void showDialog(final int position) {
            final AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(SearchReportActivity.this);
            normalDialog.setTitle("删除订单");
            normalDialog.setMessage("确定要删除此条订单吗?");
            normalDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            delete(position);
                        }

                    });

            normalDialog.setNegativeButton("取消",

                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }

                    });

            // 显示

            normalDialog.show();

        }


        class ViewHolder {
            TextView mBrand;
            TextView mStatus;
            TextView mVin;
            TextView mTime;
            ImageButton mDelete;
            ImageView mIvLog;
        }
    }

    /**
     * 删除报告
     */
    private void delete(final int position) {
        ReportListBean.PayListBean payListBean = mReportListBean.getPayList().get(position);
        String payListId = payListBean.getId();
        OkHttpUtils.post().url(Constants.DELETE_PAYLIST_URL).addParams("carBusinessId", mBusinessid).addParams("payListId", payListId)
                .addParams("sign", Constants.SIGN).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                MyToast.show("请求失败,请检查网络...");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String success = (String) jsonObject.get("success");
                    String message = (String) jsonObject.get("message");
                    if (TextUtils.equals("00", success)) {
                        if (mReportListAdapter != null) {
                            ReportListBean.PayListBean item = (ReportListBean.PayListBean) mReportListAdapter.getItem(position);
                            mReportListBean.getPayList().remove(item);
                            mReportListAdapter.notifyDataSetChanged();
                        }
                    } else {
                        MyToast.show(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });
    }
}
